<template>
  <view class="container">
    <scroll-view
      class="conversation-list"
      scroll-y
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view
        v-for="conv in conversations"
        :key="conv.id"
        class="conversation-item"
        @click="goToChat(conv)"
      >
        <view class="avatar-wrapper">
          <u-avatar :src="conv.otherUser.avatar" size="48"></u-avatar>
          <view v-if="conv.unreadCount > 0" class="unread-badge">
            {{ conv.unreadCount > 99 ? '99+' : conv.unreadCount }}
          </view>
        </view>

        <view class="conversation-content">
          <view class="conversation-header">
            <text class="nickname">{{ conv.otherUser.nickname }}</text>
            <text class="time">{{ formatRelativeTime(conv.updatedAt) }}</text>
          </view>
          <view class="last-message">
            <text class="text-ellipsis">{{ formatMessageContent(conv.lastMessage) }}</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && conversations.length === 0" class="empty-state">
        <u-empty mode="list" text="暂无消息"></u-empty>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'
import { useChatStore } from '@/store/chat'
import { formatRelativeTime } from '@/utils/format'
import type { Conversation } from '@/types'

const chatStore = useChatStore()

// 状态
const conversations = ref<Conversation[]>([])
const loading = ref(false)
const refreshing = ref(false)

// 生命周期
onMounted(() => {
  loadConversations()
})

onShow(() => {
  // 从聊天详情页返回时刷新列表
  loadConversations()
})

// 下拉刷新
onPullDownRefresh(async () => {
  await onRefresh()
  uni.stopPullDownRefresh()
})

/**
 * 加载会话列表
 */
const loadConversations = async () => {
  loading.value = true

  try {
    await chatStore.fetchConversations()
    conversations.value = chatStore.conversations
  } catch (err) {
    console.error('加载会话列表失败:', err)
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/**
 * 刷新
 */
const onRefresh = async () => {
  refreshing.value = true
  await loadConversations()
}

/**
 * 格式化消息内容
 */
const formatMessageContent = (lastMessage: any): string => {
  if (!lastMessage) return ''

  switch (lastMessage.contentType) {
    case 'text':
      return lastMessage.content
    case 'image':
      return '[图片]'
    case 'voice':
      return '[语音]'
    case 'location':
      return '[位置]'
    default:
      return '[消息]'
  }
}

/**
 * 跳转到聊天页面
 */
const goToChat = (conv: Conversation) => {
  uni.navigateTo({
    url: `/pages/chat/detail?conversationId=${conv.id}&userId=${conv.otherUser.id}`
  })
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background-color: var(--bg-color-page);
}

.conversation-list {
  height: 100%;
}

.conversation-item {
  display: flex;
  padding: var(--spacing-md);
  background-color: var(--bg-color);
  border-bottom: 1rpx solid var(--border-color-lighter);

  &:active {
    background-color: var(--bg-color-page);
  }

  .avatar-wrapper {
    position: relative;
    margin-right: var(--spacing-md);

    .unread-badge {
      position: absolute;
      top: -8rpx;
      right: -8rpx;
      min-width: 32rpx;
      height: 32rpx;
      padding: 0 8rpx;
      background-color: var(--error-color);
      color: #ffffff;
      font-size: 20rpx;
      border-radius: var(--radius-round);
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid var(--bg-color);
    }
  }

  .conversation-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .conversation-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8rpx;

      .nickname {
        font-size: 32rpx;
        font-weight: 500;
        color: var(--text-color);
      }

      .time {
        font-size: 24rpx;
        color: var(--text-color-placeholder);
      }
    }

    .last-message {
      font-size: 28rpx;
      color: var(--text-color-secondary);
    }
  }
}

.empty-state {
  padding: 200rpx 0;
}
</style>
